﻿using GodSystemBLL;
using GodSystemCommon;
using GodSystemModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GodSystem.FormChildren
{
    public partial class FormProductAdd : Form
    {
        public FormProductAdd()
        {
            InitializeComponent();
            InitData();
        }

        private void button_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
            this.Dispose();
        }

        private void InitData()
        {
            CateBLL cateBLL = new CateBLL();
            DataTable cateList = cateBLL.GetCategories();
            ArrayList textValue = new ArrayList();

            if(cateList.Rows.Count > 0)
            {
                for(int i = 0; i < cateList.Rows.Count; i++)
                {
                    uint cateId = cateList.Rows[i].Field<uint>("Id");
                    string cateIds = Convert.ToString(cateId);
                    string cateName = cateList.Rows[i].Field<string>("CateName");
                    textValue.Add(new TextAndValue(cateName,cateIds));
                }
            }

            comboBox_CateId.DataSource = textValue;
            comboBox_CateId.DisplayMember = "DisplayText";
            comboBox_CateId.ValueMember = "RealValue";

            ArrayList textValueForStaus = new ArrayList();
            textValueForStaus.Add(new TextAndValue("正常", "1"));
            textValueForStaus.Add(new TextAndValue("草稿", "0"));
            textValueForStaus.Add(new TextAndValue("冻结", "2"));

            comboBox_ProductStatus.DataSource = textValueForStaus;
            comboBox_ProductStatus.DisplayMember = "DisplayText";
            comboBox_ProductStatus.ValueMember = "RealValue";
        }


        private void button_UploadPic_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "选择要上传的图片";
            // ofd.Filter = "图片|*.gif;*.jpg;*.jpeg;*.bmp;*.jfif;*.png;|文档|*.doc;|Excel|*.xls;*.xlsx"
            ofd.Filter = "图片|*.gif;*.jpg;*.jpeg;*.bmp;*.png;";
            DialogResult dr = ofd.ShowDialog();
            string fileName = ofd.FileName;
            if (!File.Exists(fileName))
            {
                MessageBox.Show("图片为空，请选择图片","提示",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            if(dr == DialogResult.OK)
            {
                // 获取文件扩展名
                string extensionName = Path.GetExtension(fileName);
                pictureBox1.Image = Image.FromFile(fileName);
                pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                Random random = new Random();
                int randNum = random.Next(10000, 9999999);
                // 目录
                string imageSubdiretory = DateTime.Now.ToString("yyyyMMdd");
                // 文件名
                string newImageFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + randNum.ToString();
                // 程序当前目录
                string currentDir = Environment.CurrentDirectory;
                
                string rootPath = currentDir.Substring(0, currentDir.LastIndexOf("\\"));
                // .../GodSystem
                rootPath = rootPath.Substring(0, rootPath.LastIndexOf("\\"));
                // 新目录
                string newDirectoryPath = rootPath + "\\ProductImages\\" + imageSubdiretory;
                Utility.CreateDirectory(newDirectoryPath);
                string newFilePath = newDirectoryPath + "\\" + newImageFileName + extensionName;
                string relativePath = "ProductImages\\" + imageSubdiretory +"\\"+ newImageFileName + extensionName;
                pictureBox1.Tag = relativePath;
                File.Copy(fileName, newFilePath);
            }
        }

        private void textBox_PicUrl_Leave(object sender, EventArgs e)
        {
            string picUrl = textBox_PicUrl.Text.Trim();
            if (!string.IsNullOrEmpty(picUrl))
            {
                string http = picUrl.Substring(0, 5);
                if (http.Contains("http"))
                {
                    pictureBox1.Image = null;
                    pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
                    pictureBox1.Tag = picUrl;
                    pictureBox1.Load(picUrl);
                }
            }
        }


        private bool IsNumber(char kc, TextBox textBox)
        {

            if ((kc >= 48 && kc <= 57) || kc == 8)
                return true;
            else if (kc == 46)                       //小数点
            {
                if (textBox.Text.Length <= 0)
                    return false;     //小数点不能在第一位
                else
                {
                    float f;
                    float oldf;
                    bool b1 = false, b2 = false;
                    b1 = float.TryParse(textBox.Text, out oldf);
                    b2 = float.TryParse(textBox.Text + kc.ToString(), out f);
                    if (b2 == false)
                    {
                        if (b1 == true)
                            return false;
                        else
                            return true;
                    }
                    else
                    {
                        return true;
                    }
                }
            }
            else
            {
                return false;
            }
        }




        private void textAbs_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            if (IsNumber(e.KeyChar, textBox))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }


        private void button_Submit_Click(object sender, EventArgs e)
            {
            string cateIds = comboBox_CateId.SelectedValue.ToString();
            int cateId = Convert.ToInt32(cateIds);
            string productName = textBox_ProductName.Text.Trim();
            string productSn = textBox_ProductSn.Text.Trim();
            string productMainSku = textBox_MainSku.Text.Trim();
            string productWeight = textBox_Weight.Text.Trim();
            string productPrice = textBox1_PurchasePrice.Text.Trim();
            string picUrl = textBox_PicUrl.Text.Trim();
            string productStatus = comboBox_ProductStatus.SelectedValue.ToString();
            string picPath = "";
            if(pictureBox1.Image != null)
            {
                picPath = pictureBox1.Tag.ToString();
            }

            if (string.IsNullOrEmpty(productName))
            {
                MessageBox.Show("产品名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(productName))
            {
                MessageBox.Show("产品名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(cateIds))
            {
                MessageBox.Show("分类不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(productSn))
            {
                MessageBox.Show("SKU不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(productMainSku))
            {
                MessageBox.Show("主SKU不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(productWeight))
            {
                productWeight = "0";
            }

            if (string.IsNullOrEmpty(productPrice))
            {
                productPrice = "0";
            }


            ProductsBLL productsBLL = new ProductsBLL();
            object num = productsBLL.CheckProductSn(productSn);
            int total = Convert.ToInt32(num);
            if(total > 0)
            {
                MessageBox.Show("此产品编号已经存在，请更换", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ProductsModel product = new ProductsModel();
            product.ProductName = productName;
            product.ProductSn = productSn;
            product.SupplierId = 0;
            product.ProductStatus = Convert.ToInt32(productStatus);
            product.CreateTime = DateTime.Now;
            product.CateId = Convert.ToInt32(cateIds);
            product.MainSku = productMainSku;
            product.Weight = Convert.ToDecimal(productWeight);
            product.PurchasePrice = Convert.ToDecimal(productPrice);
            product.ProductThumbImage = picPath;
            int result = productsBLL.AddProduct(product);
            if (result > 0)
            {
                MessageBox.Show("添加成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                textBox_ProductName.Text = "";
                textBox_ProductSn.Text = "";
                textBox_MainSku.Text = "";
                textBox_Weight.Text = "";
                textBox1_PurchasePrice.Text = "";
                textBox_PicUrl.Text = "";
                if(pictureBox1.Image != null)
                {
                    pictureBox1.Tag = "";
                    pictureBox1.Image = null;
                }
                
            }
            else
            {
                MessageBox.Show("添加失败，请稍后再试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }





        }
    }
}
